package com.lee.config;

import com.mysql.cj.jdbc.MysqlConnectionPoolDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;

import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;

@EnableJpaRepositories(basePackages = "com.lee.dao")
public class JpaConfig {

    /**
     * 此类相当于
     * <jpa:repositories base-package="com.acme.repositories"/>
     */

    @Bean
    DataSource dataSource() {

        /**
         * 获取配置文件
         */
        Properties jdbcProperties = new Properties();
        File file = new File("jdbc.properties");
        try (FileInputStream inputStream = new FileInputStream(file)) {
            jdbcProperties.load(inputStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        /**
         * 配置数据源
         */
        MysqlConnectionPoolDataSource mysqlPool = new MysqlConnectionPoolDataSource();
        mysqlPool.setURL(jdbcProperties.getProperty("url"));
        mysqlPool.setUser(jdbcProperties.getProperty("user"));
        mysqlPool.setPassword(jdbcProperties.getProperty("password"));
        return mysqlPool;
    }


//    @Bean(name = "entityManager")
//    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
//        return entityManagerFactorySec(builder).getObject().createEntityManager();
//    }

//    @Bean(name = "entityManagerFactory")
//    public LocalContainerEntityManagerFactoryBean entityManagerFactorySec(
//            EntityManagerFactoryBuilder builder, @Autowired DataSource dataSource) {
//        Map<String, Object> properties = hibernateProperties.determineHibernateProperties(jpaProperties.getProperties(), new HibernateSettings());
//        return builder.dataSource(dataSource)
//                .properties(properties)
//                .packages("com.my.entity") //设置实体类所在位置
//                .persistenceUnit("secPersistenceUnit")
//                .build();
//    }

//    @Bean(name = "transactionManagerSec")
//    PlatformTransactionManager transactionManagerSec(EntityManagerFactoryBuilder builder) {
//        return new JpaTransactionManager(entityManagerFactorySec(builder).getObject());
//    }


}
